const path = require('path');
const minimist = require('minimist');
const CompressionPlugin = require('compression-webpack-plugin');
const {
  override,
  fixBabelImports,
  addBabelPlugin,
  // addLessLoader,
  addWebpackPlugin,
  addWebpackAlias,
  overrideDevServer,
  setWebpackOptimizationSplitChunks,
} = require('customize-cra');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');

const isGzip = process.env.NODE_ENV === 'production';

const options = minimist(process.argv.slice(2));

const server = options.t ? process.env.TEST_SERVER : process.env.DEV_SERVER;

const addProxy = () => (configFunction) => {
  // 代理地址表，默认代理域名为.env文件中配置的地址
  // 如存在特殊域名地址，请使用数组配置，并传递数组的第二个参数
  const proxyMap = [
    // '/finchinaAPP/xinsight',
    // ['/cloudInfo', 'https://xinsight.finchina.com/cloudInfo'],
    // '/finchinaPC',
    // '/refresh.action',
    // '/getData.action',
    // '/getWebsocket',
    // '/project',
    // '/receive.action',
    // '/jquery',
    // ['/template', `https://${server}/finchinaPC`],
  ];
  const baseProxyConfig = {
    secure: false,
    changeOrigin: false,
  };
  configFunction.proxy = proxyMap.reduce((proxyConfig, config) => {
    if (Array.isArray(config)) {
      const [proxyUrl, redirectUrl] = config;
      return Object.assign(proxyConfig, {
        [proxyUrl]: Object.assign({}, baseProxyConfig, {
          target: redirectUrl,
          pathRewrite: { [`^${proxyUrl}`]: '' },
        }),
      });
    } else {
      return Object.assign(proxyConfig, {
        [config]: Object.assign({}, baseProxyConfig, {
          target: `https://${server}${config}`,
          pathRewrite: { [`^${config}`]: '' },
        }),
      });
    }
  }, {});
  // configFunction.https = true;
  return configFunction;
};

module.exports = {
  webpack: override(
    addBabelPlugin([
      'babel-plugin-styled-components',
      {
        displayName: process.env.NODE_ENV === 'development',
      },
    ]),
    addBabelPlugin(['@babel/plugin-proposal-optional-chaining']),
    process.env.NODE_ENV === 'production' &&
      addBabelPlugin(['babel-plugin-transform-remove-console', { exclude: ['error', 'warn'] }]),
    fixBabelImports('import', {
      libraryName: 'antd',
      libraryDirectory: 'es',
      style: true,
    }),
    fixBabelImports('lodash', {
      libraryName: 'lodash',
      libraryDirectory: '',
      camel2DashComponentName: false,
    }),
    fixBabelImports('@umijs/hooks', {
      libraryName: '@umijs/hooks',
      libraryDirectory: 'es',
      camel2DashComponentName: false,
      customName: (name) => {
        if (name === 'useRequest') {
          return '@umijs/use-request';
        }
        return `@umijs/hooks/es/${name}`;
      },
    }),
    // addLessLoader({
    //   javascriptEnabled: true,
    //   cssModules: {
    //     localIdentName:
    //       process.env.NODE_ENV === 'development'
    //         ? '[path][name]__[local]--[hash:base64:5]'
    //         : 'qyyjt-[sha512:hash:base64:7]',
    //   },
    // }),
    addWebpackAlias({
      '@': path.resolve(__dirname, 'src'),
      // less: path.resolve(__dirname, 'src/assets/styles/less'),
    }),
    addWebpackPlugin(new AntdDayjsWebpackPlugin()),
    addWebpackPlugin(new ProgressBarPlugin()),
    isGzip && addWebpackPlugin(new CompressionPlugin()),
    setWebpackOptimizationSplitChunks({
      chunks: 'all',
      name: false,
      cacheGroups: {
        common: {
          name: 'common',
          chunks: 'all',
          minChunks: 4,
          minSize: 1,
          priority: 0,
          reuseExistingChunk: true,
          enforce: true,
        },
        vendors: {
          name: 'vendor',
          test: /[\\/]node_modules[\\/]/,
          minSize: 50000,
          minChunks: 2,
          chunks: 'initial',
          priority: 1,
        },
        echarts: {
          name: 'echarts',
          priority: 20,
          test: /[\\/]node_modules[\\/](echarts|zrender)[\\/]/,
          chunks: 'all',
        },
        'react-lib': {
          name: 'react-lib',
          priority: 20,
          test: /[\\/]node_modules[\\/](react|react-dom|react-router-dom|redux|react-redux)[\\/]/,
          chunks: 'all',
        },
        antd: {
          name: 'antd',
          priority: 20,
          test: /[\\/]node_modules[\\/](antd|@ant-design)[\\/]/,
          chunks: 'all',
        },
      },
    }),
  ),
  devServer: overrideDevServer(addProxy()),
};
